package com.lvmama.pangolin.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class RedisRepository {
	/**   
	* @Title: RedisRepository.java  
	* @Description: TODO(用一句话描述该文件做什么) 
	* @author ZhouTianQi   
	* @date 2017年2月7日 下午3:49:01 
	* @version V1.0   
	*/
    @Autowired 
    private RedisTemplate<String, String> redisTemplate;

    public <T> void add(String key, Long time,T t) {
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(key, gson.toJson(t), time, TimeUnit.MINUTES);
    }

    public <T> void add(String key, Long time, List<T> t) {
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(key, gson.toJson(t), time, TimeUnit.MINUTES);
    }

	public <T> T get(String key,Class<T> clazz) {
        Gson gson = new Gson();
        T k = null;
        String tJson = redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(tJson))
            k = (T) gson.fromJson(tJson, clazz);
        return k;
    }

    public <T> List<T> getList(String key) {
        Gson gson = new Gson();
        List<T> ts = null;
        String listJson = redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(listJson))
            ts = gson.fromJson(listJson, new TypeToken<List<T>>(){}.getType());
        return ts;
    }

    public void delete(String key){
        redisTemplate.opsForValue().getOperations().delete(key);
    }
}
